# @author: Samuel Taylor <samtaylor.uk@gmail.com>
# @package: winecellar
# @license: GNU GPLv3
#
# Copyright (C) 2010  Samuel Taylor <samtaylor.uk@gmail.com>
#----------------------------------------------------------------------
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#-----------------------------------------------------------------------

__author__ = 'Samuel Taylor <samtaylor.uk@gmail.com>'

import os
from lxml import etree
import WineCellar.Config
from WineCellar.Logger import logger

class Preferences:
    def __init__(self):
        self.defaultXML()
        
    def getRepositories(self):
        parser = etree.XMLParser(remove_blank_text=True)
        tree = etree.parse(str(WineCellar.Config.__configpath__), parser)
        repositories = {}

        i = 0
        for element in tree.iter("repository"):
            try:
                id = element.attrib['id']
            except:
                id = None
            
            try:
                name = element.attrib['name']
            except:
                name = None
            
            repositories[i] = {"url" : element.text, "id" : id, "name" : name}
            i += 1
        
        return repositories

    def getKey(self, key):
        parser = etree.XMLParser(remove_blank_text=True)
        tree = etree.parse(str(WineCellar.Config.__configpath__), parser)

        return tree.find(key).text

    def setKey(self, key, value):
        self.unsetKey(key)
        
        parser = etree.XMLParser(remove_blank_text=True)
        tree = etree.parse(str(WineCellar.Config.__configpath__), parser)
        root = tree.getroot()
        
        etree.SubElement(root, key).text = value

        f = open(str(WineCellar.Config.__configpath__), 'w')
        f.write(etree.tostring(tree, pretty_print=True, encoding='iso-8859-1'))
        f.close()

    def unsetKey(self, key):
        parser = etree.XMLParser(remove_blank_text=True)
        tree = etree.parse(str(WineCellar.Config.__configpath__), parser)

        tree.find(key).clear()
        
        f = open(str(WineCellar.Config.__configpath__), 'w')
        f.write(etree.tostring(tree, pretty_print=True, encoding='iso-8859-1'))
        f.close()
    
    def keyExist(self,key):
        """
        Checks to see if key exists
        """
        parser = etree.XMLParser(remove_blank_text=True)
        tree = etree.parse(str(WineCellar.Config.__configpath__), parser)

        try:
            if tree.find(key).text == None:
                return False
            else:
                return True
        except:
            return False
        
    def defaultXML(self):
        """
        Checks to see if config.xml exists, 
        if does not exist will create a default config xml.
        """
        if not os.path.exists(str(WineCellar.Config.__apphome__)):
            os.makedirs(str(WineCellar.Config.__apphome__))
        
        if not os.path.exists(str(WineCellar.Config.__configpath__)):
            configXML = etree.Element("preferences")
            
            etree.SubElement(configXML, "repository").text = "http://winecellar.samueltaylor.me.uk/"
            etree.SubElement(configXML, "owner").text = "na"
            etree.SubElement(configXML, "company").text = "na"
            
            f = open(str(Config.__configpath__), 'w')
            f.write(etree.tostring(configXML, pretty_print=True, encoding='iso-8859-1'))
            f.close()
